/**
 * 页面访问 MongoDB Schema
 */

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

export type PageViewDocument = PageView & Document;

@Schema({ collection: 'page_views', timestamps: true })
export class PageView {
  @Prop({ required: true, type: Types.ObjectId, ref: 'Website', index: true })
  websiteId: Types.ObjectId;

  @Prop({ required: true, index: true })
  url: string;

  @Prop()
  title?: string;

  @Prop()
  referrer?: string;

  @Prop()
  userAgent?: string;

  @Prop({ index: true })
  ip?: string;

  @Prop()
  country?: string;

  @Prop()
  city?: string;

  @Prop()
  browser?: string;

  @Prop()
  os?: string;

  @Prop()
  device?: string;

  @Prop()
  screenSize?: string;

  @Prop()
  language?: string;

  @Prop({ type: Object })
  customData?: Record<string, any>;

  @Prop({ default: 0 })
  timeOnPage: number;

  @Prop({ default: false })
  isUnique: boolean;

  @Prop({ index: true })
  sessionId?: string;

  // MongoDB 自动生成的字段
  createdAt?: Date;
  updatedAt?: Date;
}

export const PageViewSchema = SchemaFactory.createForClass(PageView);

// 创建索引
PageViewSchema.index({ websiteId: 1, createdAt: -1 });
PageViewSchema.index({ url: 1, createdAt: -1 });
PageViewSchema.index({ ip: 1, createdAt: -1 });
PageViewSchema.index({ sessionId: 1 });
PageViewSchema.index({ isUnique: 1 });
PageViewSchema.index({ createdAt: -1 });
